package com.woniuxy.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.Result;
import com.woniuxy.exception.WoniuxyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class ExceptionHandler implements ErrorWebExceptionHandler {

    private ObjectMapper om = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        System.out.println(ex);
        log.error("出现异常: ",ex);
        Result<?> result = Result.getInstance();
        if(ex instanceof WoniuxyException) {
            WoniuxyException pe = (WoniuxyException)ex;
            result.setCode(pe.getCode()).setMsg(pe.getMessage());
        } else {
            result.setCode(500).setMsg("出现错误");
        }
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        try {
            final String json = om.writeValueAsString(result);
            //做响应
            return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
                return exchange.getResponse().bufferFactory().wrap(json.getBytes());
            }));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
